package 练习02_多线程穷举法破解密码;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: PassWordThread
 * @Author: AllenSun
 * @Date: 2022/3/18 下午9:04
 */
public class PassWordThread implements Runnable {


    //第二步：把需要的参数和构造器写好
    private String pwd;
    private List<String> pwdList;

    public PassWordThread(String pwd, List<String> pwdList) {
        this.pwd = pwd;
        this.pwdList = pwdList;
    }

    //第三步：完善run方法
    @Override
    public void run() {
        char[] guessPwd = new char[pwd.length()];
        generatePwd(guessPwd,pwd);
    }

    //第一步：把穷举法生成密码并且进行匹配的方法写好
    //如果匹配到密码了就停止遍历
    private boolean found = false;

    public void generatePwd(char[] guessPwd,String pwd) {
        generatePwd(guessPwd,0,pwd);
    }

    public void generatePwd(char[] guessPwd,int index,String pwd) {
/*        //一个和密码等长度的字符型数组
        char[] guessPwd = new char[pwd.length()];
        //一个计数值
        int index = 0;*/
        //遍历数值和字母来生成密码
        if(found){
            return;
        }
        for (short i='0';i<'z';i++) {
            if(!Character.isLetterOrDigit(i)){
                continue;
            }
            char c = (char) i;
            guessPwd[index] = c;
            if(index==pwd.length()-1){
                //把三个字母的数组拼接成字符串
                String guessResult = new String(guessPwd);
                pwdList.add(guessResult);
                if(guessResult.equals(pwd)){
                    System.out.println("密码找到了，是："+guessResult);
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    System.out.println("当前时间是："+df.format(new Date()));
                    found = true;
                    return;
                }
            } else {
                generatePwd(guessPwd,index+1,pwd);
            }
        }


    }

}
